import time
import requests
import urllib
import os
from bs4 import BeautifulSoup


def SaveImage(link,InputData,count):
    try:
        time.sleep(0.2)
        urllib.request.urlretrieve(link,'./'+InputData+'/'+str(count)+'.jpg')
    except Exception :
        time.sleep(1)
        print("产生未知错误，放弃保存")
    else:
        print("图+1,已有" + str(count) + "张图")

if __name__ == "__main__" :
        word = 'images'
        haeders = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36'}
        data = {'q': '图片', 'first': 1, 'count': 35, 'lostate': 'r', 'mmasync': 1,
                'dgState': 'x*175_y*848_h*199_c*1_i*106_r*0'}
        url = 'http://cn.bing.com/images/async'
        info = requests.get(url=url, params=data, headers=haeders)
        soup = BeautifulSoup(info.text, features='html.parser')
        # print(soup.prettify())
        # print(type(soup.img))
        list = soup.findAll('img')
        if not os.path.exists(word):
            os.mkdir(word)
        for item in list:
            path = item.attrs['src']
            count = len(os.listdir('./' + word)) + 1
            SaveImage(path, word, count)